package com.spddr.pmos.cxf.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spddr.pmos.cxf.JaxrsContractPlan;
import com.spddr.pmos.jpa.ContractPlan;
import com.spddr.pmos.repos.ContractPlanRepos;

@Service
public class JaxrsContractPlanImpl  implements JaxrsContractPlan{

	@Autowired
	ContractPlanRepos contractPlanRepos;

	@Override
	public JpaRepository<ContractPlan, Long> getRepository() {
		return contractPlanRepos;
	}

	@Override
	public Integer saveall(String param) {
		SimpleDateFormat  sdf = new SimpleDateFormat("yyyy-MM");
		String newParam="";
		if(null!=param&&!param.equals("")){
			newParam = param.replace("^", "[");
			newParam = newParam.replace("*", "]");
		}
		ObjectMapper mapper = new ObjectMapper();
		try {
			List<ContractPlan> lendReco = (List<ContractPlan>)mapper.readValue(newParam,new TypeReference<List<ContractPlan>>() { });
			if(lendReco.size()>0){
				for(ContractPlan mm:lendReco){
					mm.setDisable(1);
					mm.setMonth(sdf.format(new Date()));
					contractPlanRepos.save(mm);
				}
			}
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
		
		System.out.println(param);
		return 1;
	}

	@Override
	public List<ContractPlan> findAll(Long id) throws ParseException {
		// TODO Auto-generated method stub
		return contractPlanRepos.findByOrgPlantAndDisable(id, 1);
	}

}
